import {useEffect, useState} from 'react'
import s from './Item.module.css'
import {Button, Checkbox, DialogPlugin, MessagePlugin, RangeInput, Space, Table, Textarea} from "tdesign-react";
import {ClearIcon, CodeIcon, CopyIcon, RefreshIcon} from "tdesign-icons-react";
import {copy} from "../../utils/common";

const Item = () => {

    const [data, setData] = useState([])

    const [total, setTotal] = useState({total: 0})

    const [filter, setFilter] = useState([])

    const [pagination, setPagination] = useState({page: 1, pageSize: 30})

    const [tableHeight, setTableHeight] = useState(100)

    const [checkOptions, setCheckOptions] = useState({hero: false, epic: false})

    const queryCallback = (res) => {
        if (res.status === 'ok') {
            setData(res.data)
        } else {
            MessagePlugin.error("数据拉取失败！请检查数据库是否启动！").then()
        }
    }

    const handleQuery = (f = filter, p = pagination) => {
        window?.electronAPI?.queryItems(f, p, queryCallback)
        window?.electronAPI?.getItemsCount(f, setTotal)

        setFilter(f)
        setPagination(p)
    }

    useEffect(() => {
        handleQuery()
    }, []);

    const classOptions = [
        {
            label: '消耗品', value: 0, children: [
                {label: '炸弹', value: 0},
                {label: '药水', value: 1},
                {label: '药剂', value: 2},
                {label: '合剂', value: 3},
                {label: '卷轴', value: 4},
                {label: '食物', value: 5},
                {label: '物品强化', value: 6},
                {label: '绷带', value: 7},
                {label: '其他', value: 8},
                {label: '凡图斯符文', value: 9},
            ]
        },
        {
            label: '容器', value: 1, children: [
                {label: '容器', value: 0},
                {label: '灵魂袋', value: 1},
                {label: '草药', value: 2},
                {label: '附魔', value: 3},
                {label: '工程', value: 4},
                {label: '宝石', value: 5},
                {label: '矿石', value: 6},
                {label: '制皮', value: 7},
                {label: '铭文', value: 8},
                {label: '工具', value: 9},
                {label: '烹饪', value: 10},
            ]
        },
        {
            label: '武器', value: 2, children: [
                {label: '单手斧', value: 0},
                {label: '双手斧', value: 1},
                {label: '弓', value: 2},
                {label: '枪械', value: 3},
                {label: '单手锤', value: 4},
                {label: '双手锤', value: 5},
                {label: '长柄武器', value: 6},
                {label: '单手剑', value: 7},
                {label: '双手剑', value: 8},
                {label: '战刃', value: 9},
                {label: '法杖', value: 10},
                {label: '熊爪', value: 11},
                {label: '豹爪', value: 12},
                {label: '拳套', value: 13},
                {label: '其他', value: 14},
                {label: '匕首', value: 15},
                {label: '投掷武器', value: 16},
                {label: '矛', value: 17},
                {label: '弩', value: 18},
                {label: '魔杖', value: 19},
                {label: '鱼竿', value: 20},
            ]
        },
        {
            label: '宝石', value: 3, children: [
                {label: '智力', value: 0},
                {label: '敏捷', value: 1},
                {label: '力量', value: 2},
                {label: '耐力', value: 3},
                {label: '精神', value: 4},
                {label: '暴击', value: 5},
                {label: '精通', value: 6},
                {label: '急速', value: 7},
                {label: '全能', value: 8},
                {label: '其他', value: 9},
                {label: '复合属性', value: 10},
                {label: '神器圣物', value: 11},

            ]
        },
        {
            label: '护甲', value: 4, children: [
                {label: '其他', value: 0},
                {label: '布甲', value: 1},
                {label: '皮甲', value: 2},
                {label: '锁甲', value: 3},
                {label: '板甲', value: 4},
                {label: '装饰品', value: 5},
                {label: '盾牌', value: 6},
                {label: '圣契', value: 7},
                {label: '神像', value: 8},
                {label: '图腾', value: 9},
                {label: '符印', value: 10},
                {label: '圣物', value: 11},

            ]
        },
        {
            label: '材料', value: 5, children: [
                {label: '材料', value: 0},
                {label: '钥石', value: 1},
            ]
        },
        {
            label: '弹药', value: 6, children: [
                {label: '魔杖', value: 0},
                {label: '矢', value: 1},
                {label: '箭', value: 2},
                {label: '子弹', value: 3},
                {label: '投掷武器', value: 4},
            ]
        },
        {
            label: '商业技能', value: 7, children: [
                {label: '商品', value: 0},
                {label: '零件', value: 1},
                {label: '爆炸物', value: 2},
                {label: '装置', value: 3},
                {label: '珠宝加工', value: 4},
                {label: '布料', value: 5},
                {label: '皮革', value: 6},
                {label: '金属和矿石', value: 7},
                {label: '烹饪', value: 8},
                {label: '草药', value: 9},
                {label: '元素', value: 10},
                {label: '其他', value: 11},
                {label: '附魔材料', value: 12},
                {label: '原料', value: 13},
                {label: '物品附魔', value: 14},
                {label: '武器强化', value: 15},
                {label: '铭文', value: 16},
                {label: '爆炸物与装置', value: 17},
            ]
        },
        {
            label: '物品强化', value: 8, children: [
                {label: '头部', value: 0},
                {label: '颈部', value: 1},
                {label: '肩部', value: 2},
                {label: '披风', value: 3},
                {label: '胸部', value: 4},
                {label: '手腕', value: 5},
                {label: '手部', value: 6},
                {label: '腰部', value: 7},
                {label: '腿部', value: 8},
                {label: '脚部', value: 9},
                {label: '手指', value: 10},
                {label: '武器', value: 11},
                {label: '双手武器', value: 12},
                {label: '盾牌/副手', value: 13},
                {label: '其他', value: 14},
            ]
        },
        {
            label: '配方', value: 9, children: [
                {label: '书籍', value: 0},
                {label: '制皮', value: 1},
                {label: '裁缝', value: 2},
                {label: '工程学', value: 3},
                {label: '锻造', value: 4},
                {label: '烹饪', value: 5},
                {label: '炼金术', value: 6},
                {label: '急救', value: 7},
                {label: '附魔', value: 8},
                {label: '钓鱼', value: 9},
                {label: '珠宝', value: 10},
                {label: '铭文', value: 11},
            ]
        },
        {label: '箭袋', value: 11, children: []},
        {label: '任务', value: 12, children: []},
        {label: '钥匙', value: 13, children: []},
        {
            label: '杂项', value: 15, children: [
                {label: '垃圾', value: 0},
                {label: '材料', value: 1},
                {label: '宠物小伙伴', value: 2},
                {label: '节日', value: 3},
                {label: '其他', value: 4},
                {label: '坐骑', value: 5},
            ]
        },
        {
            label: '雕纹', value: 16, children: [
                {label: '战士', value: 0},
                {label: '圣骑', value: 1},
                {label: '猎人', value: 2},
                {label: '盗贼', value: 3},
                {label: '牧师', value: 4},
                {label: '萨满', value: 5},
                {label: '法师', value: 6},
                {label: '术士', value: 7},
                {label: '小德', value: 8},
                {label: 'DK', value: 9},
                {label: '武僧', value: 10},
                {label: 'DH', value: 11},
            ]
        },
        {label: '战斗宠物', value: 17, children: []},
    ]

    const getClassOptions = () => classOptions.map(item => ({label: item.label, value: item.value}))
    const getSubClassOptions = () => {
        let classId = filter.find(f => f.field === 'ClassID')
        let subClassId = classOptions.find(s => s.value === classId?.value)
        return subClassId?.children || []
    }

    const getClassLabel = (v) => {
        let classId = classOptions.find(f => f.value === v)
        return classId?.label || "未知"
    }

    const getSubClassLabel = (i, j) => {
        let classId = classOptions.find(f => f.value === i)
        let subClass = (classId?.children || []).find(g => g.value === j)
        return subClass?.label || "未知"
    }


    const filterOperationSet = {
        "Display": "like",
        "ItemLevel": "between",
        "RequiredLevel": "between",
        "ClassID": "=",
        "SubclassID": "in",
        "InventoryType": "in",
        "OverallQualityID": "in",
    }

    const onFilterChange = (filters) => {
        console.log(filters)
        let f = []
        Object.keys(filters).forEach(k => {
            let v = filters[k]
            let condition1 = (typeof v) !== "object" && (!!filters[k] || filters[k] === 0)
            let condition2 = !!filters[k]?.length
            if (condition1 || condition2) {
                f.push({
                    field: k === 'InventoryType' ? "a.InventoryType" : k,
                    operation: filterOperationSet[k],
                    value: v
                })
            }
        })
        handleQuery(f, pagination)
    }

    const inventoryTypeOptions = [
        {label: '头', value: 1},
        {label: '项链', value: 2},
        {label: '肩膀', value: 3},
        {label: '衬衣', value: 4},
        {label: '胸甲', value: 5},
        {label: '腰带', value: 6},
        {label: '腿甲', value: 7},
        {label: '鞋子', value: 8},
        {label: '护腕', value: 9},
        {label: '护手', value: 10},
        {label: '戒指', value: 11},
        {label: '饰品', value: 12},
        {label: '单手武器', value: 13},
        {label: '盾牌', value: 14},
        {label: '弓', value: 15},
        {label: '披风', value: 16},
        {label: '双手武器', value: 17},
        {label: '包包', value: 18},
        {label: '战袍', value: 19},
    ]

    const inventoryTypeSet = {}

    inventoryTypeOptions.forEach(i => inventoryTypeSet[i.value] = i.label)

    const qualityOptions = [
        {label: '粗糙(灰色)', value: 0},
        {label: '普通(白色)', value: 1},
        {label: '精致(绿色)', value: 2},
        {label: '稀有(蓝色)', value: 3},
        {label: '史诗(紫色)', value: 4},
        {label: '传说(橙色)', value: 5},
        {label: '神器', value: 6},
        {label: '传家宝', value: 7},
    ]

    const qualitySet = {}

    qualityOptions.forEach(i => qualitySet[i.value] = i.label)

    const columns = [
        {
            colKey: 'row-select', type: 'multiple', width: 50,
        },
        {
            colKey: 'ID', title: '物品ID', width: '8%'
        },
        {
            colKey: 'Display', title: '物品名称', width: '30%',
            filter: {
                type: 'input',
                resetValue: '',
                confirmEvents: ['onEnter'],
                props: {placeholder: '输入关键词过滤'},
                showConfirmAndReset: true,
            },
        },
        {
            colKey: 'ItemLevel', title: '装备等级',
            filter: {
                component: RangeInput,
                resetValue: '',
                confirmEvents: ['onEnter'],
                props: {placeholder: ['最小装备等级', '最大装备等级']},
                showConfirmAndReset: true,
            },
        },
        {
            colKey: 'RequiredLevel', title: '使用等级',
            filter: {
                component: RangeInput,
                resetValue: '',
                confirmEvents: ['onEnter'],
                props: {placeholder: ['最小使用等级', '最大使用等级']},
                showConfirmAndReset: true,
            },
        },
        {
            colKey: 'ClassID', title: '主类型',
            filter: {
                type: 'single',
                list: getClassOptions(),
                resetValue: undefined,
                showConfirmAndReset: true,
            },
            cell: ({row, col}) => getClassLabel(row[col.colKey])
        },
        {
            colKey: 'SubclassID', title: '子类型',
            filter: {
                type: 'multiple',
                list: getSubClassOptions(),
                resetValue: undefined,
                showConfirmAndReset: true,
            },
            cell: ({row, col}) => getSubClassLabel(row.ClassID, row[col.colKey])
        },
        {
            colKey: 'InventoryType', title: '部位',
            filter: {
                type: 'multiple',
                list: inventoryTypeOptions,
                resetValue: undefined,
                showConfirmAndReset: true,
            },
            cell: ({row, col}) => inventoryTypeSet[row[col.colKey]] || "未知"
        },
        {
            colKey: 'OverallQualityID', title: '品质',
            filter: {
                type: 'multiple',
                list: qualityOptions,
                resetValue: undefined,
                showConfirmAndReset: true,
            },
            cell: ({row, col}) => qualitySet[row[col.colKey]] || "未知"
        }]

    columns.forEach(col => col.align = "center")

    const [selectedRowKeys, setSelectedRowKeys] = useState([])

    const generateCode = () => {
        let results = []
        selectedRowKeys.forEach(i => results.push(`.add ${i}`))
        if (checkOptions.hero) {
            selectedRowKeys.forEach(i => results.push(`.add ${i} 1 3439`))
        }
        if (checkOptions.epic) {
            selectedRowKeys.forEach(i => results.push(`.add ${i} 1 3440`))
        }

        return results.join("\n")
    }

    const handleCodeShow = () => {
        const alertDia = DialogPlugin.alert({
            header: "查看代码",
            body: <Textarea autosize={{maxRows: 20}} defaultValue={generateCode()}/>,
            confirmBtn: {
                content: '知道了',
                variant: 'base',
                theme: 'primary',
            },
            onConfirm: () => alertDia.hide(),
            onClose: () => alertDia.hide()
        })
    }

    const handleCopy = () => {
        copy(generateCode(), "复制成功！")
    }

    const onSelectChange = (value) => {
        setSelectedRowKeys(value);
    }

    const handleClearSelected = () => setSelectedRowKeys([])

    return (<div className={s.container}>
        <div className={s.actionBar}>
            <Space>
            </Space>
            <Space align={'center'}>
                <Checkbox
                    checked={checkOptions.hero}
                    onChange={(v) => setCheckOptions(prevState => {
                        return {...prevState, hero: v}
                    })}
                >
                    添加英雄
                </Checkbox>
                <Checkbox
                    checked={checkOptions.epic}
                    onChange={(v) => setCheckOptions(prevState => {
                        return {...prevState, epic: v}
                    })}
                >
                    添加史诗
                </Checkbox>

                <Button
                    theme="default"
                    size={"small"}
                    icon={<CodeIcon/>}
                    onClick={handleCodeShow}
                >查看代码</Button>
                <Button
                    theme="default"
                    size={"small"}
                    icon={<ClearIcon/>}
                    onClick={handleClearSelected}
                >清空选中</Button>
                <Button
                    size={"small"}
                    icon={<CopyIcon/>}
                    onClick={handleCopy}
                >复制代码</Button>
            </Space>

        </div>

        <div className={s.result} ref={ref => setTableHeight(ref?.clientHeight)}>

            <Table
                className={s.table}
                rowKey={'ID'}
                bordered={true}
                columns={columns}
                height={tableHeight - 88}
                data={data}
                pagination={{
                    current: pagination.page,
                    pageSize: pagination.pageSize,
                    total: total.total,
                    showPageSize: false,
                    showPreviousAndNextBtn: true,
                    size: "small",
                    onCurrentChange(current) {
                        handleQuery(filter, {...pagination, page: current})
                    }
                }}
                selectedRowKeys={selectedRowKeys}
                onSelectChange={onSelectChange}
                lazyLoad
                onFilterChange={onFilterChange}
            />

        </div>
    </div>)
}

export default Item
